﻿using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace WucCloud.Utility
{
    /// <summary>
    /// SqlSugar 二级缓存
    /// </summary>
    public class SqlSugarCache : ICacheService
    {
        MemoryCacheHelper cache = new MemoryCacheHelper();

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <typeparam name="V"></typeparam>
        /// <param name="key">缓存key</param>
        /// <param name="value">缓存value</param>
        public void Add<V>(string key, V value)
        {
            cache.Set(key, value);
        }

        /// <summary>
        /// 添加缓存
        /// </summary>
        /// <typeparam name="V"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="cacheDurationInSeconds"></param>
        public void Add<V>(string key, V value, int cacheDurationInSeconds)
        {
            cache.Set(key, value, cacheDurationInSeconds);
        }

        /// <summary>
        /// 缓存项是否存在
        /// </summary>
        /// <typeparam name="V">实体信息</typeparam>
        /// <param name="key">缓存Key</param>
        /// <returns></returns>
        public bool ContainsKey<V>(string key)
        {
            return cache.Exists(key);
        }

        /// <summary>
        /// 获取缓存
        /// </summary>
        /// <typeparam name="V">实体信息</typeparam>
        /// <param name="key">缓存key</param>
        /// <returns></returns>
        public V Get<V>(string key)
        {
            return cache.Get<V>(key);
        }

        /// <summary>
        /// 获取所有缓存键
        /// </summary>
        /// <typeparam name="V">实体信息</typeparam>
        /// <returns></returns>
        public IEnumerable<string> GetAllKey<V>()
        {
            return cache.GetCacheKeys();
        }

        /// <summary>
        /// 获取/创建 缓存操作
        /// </summary>
        /// <typeparam name="V"></typeparam>
        /// <param name="cacheKey">缓存键</param>
        /// <param name="create"></param>
        /// <param name="cacheDurationInSeconds"></param>
        /// <returns></returns>
        public V GetOrCreate<V>(string cacheKey, Func<V> create, int cacheDurationInSeconds = int.MaxValue)
        {
            if (cache.Exists(cacheKey))
            {
                return cache.Get<V>(cacheKey);
            }
            else
            {
                var result = create();
                cache.Set(cacheKey, result, cacheDurationInSeconds);
                return result;
            }
        }

        /// <summary>
        /// 删除缓存
        /// </summary>
        /// <typeparam name="V"></typeparam>
        /// <param name="key"></param>
        public void Remove<V>(string key)
        {
            cache.Remove(key);
        }
    }
}
